<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="25%" :title="`${drawerProps.title}-定时任务`">
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=":" :rules="rules" :model="operateDataInfo">
      <el-form-item label="beanName" prop="beanName">
        <el-input v-model="operateDataInfo.beanName" placeholder="请输入执行的bean" clearable></el-input>
      </el-form-item>
      <el-form-item label="参数" prop="params">
        <el-input v-model="operateDataInfo.params" placeholder="请输入执行参数" clearable></el-input>
      </el-form-item>
      <el-form-item label="cron表达式" prop="cronExpression">
        <el-input v-model="operateDataInfo.cronExpression" placeholder="请输入cron表达式" clearable></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="operateDataInfo.remark" placeholder="请输入备注" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getJobInfo, JobPageResult, JobSaveParam, JobUpdateParam } from "@/api/modules/job/Job";

interface DrawerProps {
  title: string;
  isSave: boolean;
  isUpdate: boolean;
  row: Partial<JobPageResult>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  enumMap?: Map<string, { [key: string]: any }[]>;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  title: "",
  isSave: false,
  isUpdate: false,
  row: {}
});

const rules = reactive({
  beanName: [{ required: true, message: "请填写执行的bean" }],
  cronExpression: [{ required: true, message: "请填写cron表达式" }]
});

const operateDataInfo = ref<JobSaveParam | JobUpdateParam>({});
const openDrawer = async (params: DrawerProps) => {
  if (params.isUpdate) {
    // 更新信息，先查询
    let { data } = await getJobInfo(params.row.id ? params.row.id : "");
    operateDataInfo.value = { ...data };
  } else if (params.isSave) {
    // 新增前的默认值
    operateDataInfo.value = {};
  }
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(operateDataInfo.value);
      ElMessage.success({ message: `${drawerProps.value.title} 成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  openDrawer
});
</script>

<style scoped lang="scss"></style>
